from flask import Flask, render_template, request, jsonify
import qrcode
from io import BytesIO
import base64
import os

app = Flask(__name__, template_folder='templates', static_folder='static')

# 确保静态文件夹存在
os.makedirs(os.path.join(app.static_folder, 'css'), exist_ok=True)
os.makedirs(os.path.join(app.static_folder, 'js'), exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate_qr', methods=['POST'])
def generate_qr():
    data = request.json
    card_num = data.get('cardNum')
    card_pass = data.get('cardPass')
    url = f"http://www.tmshare123.com/wow/hema/act/giftcard?cardNum={card_num}&cardPass={card_pass}"

    # 生成二维码
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(url)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")

    # 将二维码转换为 Base64 编码的字符串
    buffered = BytesIO()
    img.save(buffered)
    img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')

    return jsonify({'qr_code': img_str})

if __name__ == '__main__':
    app.run(debug=True)